import { ref, reactive, computed } from 'vue';
import {
    getChannelList,
    getChannelNameById,
    getChannelIdByName,
    clearChannelList,
    getChannelListSync,
    getChannelNameByIdSync,
    getChannelIdByNameSync,
    updateChannelList,
    type ChannelItem
} from '@/utils/channel';

/**
 * 渠道Hook
 */
export function useChannel() {
    // 渠道缓存
    const channelCache = reactive<ChannelItem[]>([]);

    // 加载状态
    const loading = ref(false);

    /**
     * 获取渠道列表（异步）
     */
    const getChannelListAsync = async (): Promise<ChannelItem[]> => {
        loading.value = true;
        try {
            const list = await getChannelList();
            channelCache.splice(0, channelCache.length, ...list);
            return list;
        } finally {
            loading.value = false;
        }
    };

    /**
     * 获取渠道列表（同步，从缓存）
     */
    const getChannelListSyncLocal = (): ChannelItem[] => {
        return getChannelListSync();
    };

    /**
     * 根据渠道ID获取渠道名称（异步）
     */
    const getChannelNameByIdAsync = async (channelId: string): Promise<string | null> => {
        return getChannelNameById(channelId);
    };

    /**
     * 根据渠道ID获取渠道名称（同步）
     */
    const getChannelNameByIdSyncLocal = (channelId: string): string | null => {
        return getChannelNameByIdSync(channelId);
    };

    /**
     * 根据渠道名称获取渠道ID（异步）
     */
    const getChannelIdByNameAsync = async (channelName: string): Promise<string | null> => {
        return getChannelIdByName(channelName);
    };

    /**
     * 根据渠道名称获取渠道ID（同步）
     */
    const getChannelIdByNameSyncLocal = (channelName: string): string | null => {
        return getChannelIdByNameSync(channelName);
    };

    /**
     * 清空渠道缓存
     */
    const clearChannel = () => {
        clearChannelList();
        channelCache.splice(0, channelCache.length);
    };

    /**
     * 刷新渠道数据
     */
    const refreshChannel = async () => {
        loading.value = true;
        try {
            const list = await updateChannelList();
            channelCache.splice(0, channelCache.length, ...list);
            return list;
        } finally {
            loading.value = false;
        }
    };

    return {
        channelCache: computed(() => channelCache),
        loading: computed(() => loading.value),
        // 异步方法
        getChannelList: getChannelListAsync,
        getChannelNameById: getChannelNameByIdAsync,
        getChannelIdByName: getChannelIdByNameAsync,
        // 同步方法
        getChannelListSync: getChannelListSyncLocal,
        getChannelNameByIdSync: getChannelNameByIdSyncLocal,
        getChannelIdByNameSync: getChannelIdByNameSyncLocal,
        // 工具方法
        clearChannel,
        refreshChannel
    };
}

/**
 * 单个渠道Hook
 */
export function useSingleChannel() {
    const channelList = ref<ChannelItem[]>([]);
    const loading = ref(false);
    const error = ref<string | null>(null);

    /**
     * 加载渠道
     */
    const loadChannel = async () => {
        loading.value = true;
        error.value = null;

        try {
            const list = await getChannelList();
            channelList.value = list;
        } catch (err) {
            error.value = err instanceof Error ? err.message : '加载渠道失败';
            console.error('加载渠道失败:', err);
        } finally {
            loading.value = false;
        }
    };

    /**
     * 根据ID获取名称
     */
    const getNameById = (id: string): string | null => {
        const item = channelList.value.find(item => item.id === id);
        return item ? item.name : null;
    };

    /**
     * 根据名称获取ID
     */
    const getIdByName = (name: string): string | null => {
        const item = channelList.value.find(item => item.name === name);
        return item ? item.id : null;
    };

    // 自动加载
    loadChannel();

    return {
        channelList: computed(() => channelList.value),
        loading: computed(() => loading.value),
        error: computed(() => error.value),
        loadChannel,
        getNameById,
        getIdByName
    };
} 